﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using LASGui.Classes;
using LASGui.MainService;
using System.Windows.Navigation;

namespace LASGui.Views
{
    public partial class RegistroEmpresa : Page
    {
		private readonly AuthenticatedUser _authenticatedUserManager = AuthenticatedUser.Instance;
        private readonly MainPage _mainPage;
        private List<Company> _companies;
        private  ImageSource _defaultLogo;
        private Company _company;

        #region Navegacion
        /// <summary>
        /// Evento de navegacion que se dispara al terminar la navegación a esta página.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (_authenticatedUserManager.OnlineUser == null)
            {
                LogOff();
            }

            InitializeComponent();

            Logo.Source = Logo_Details.Source = new BitmapImage();
            _defaultLogo = Logo.Source;
            GetCompanies();
            GetCurrencies();
        }

        /// <summary>
        /// Método que obliga al usuario a salir de su sesión si se presenta un error de conexión o si intenta accesar a un zona reestringida sin haberse autenticado primero.
        /// </summary>
        public void LogOff()
        {
            _authenticatedUserManager.OnlineUser = null;
            NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
            var mainPage = ((App)Application.Current).Mainpage;
            mainPage.HideMainMenu();
        }
        #endregion
		
        #region Mouse events
        private void ShowCompanyInfo(object sender, SelectionChangedEventArgs e)
        {
            _company = _companies[InputEmpresas.SelectedIndex];
            try
            {
                InputIdentification_Details.Text = _company.TaxIdentification;
                //Logo.Source = ImageFromBuffer(_company.Logo);
                //InputCurrency_Details.SelectedValue = _company.SystemCurrency.CurrencyName;
                //InputLocalCurrency_Details.SelectedValue = _company.LocalCurrency.CurrencyName;

            }
            catch
            {
                ChildWindow errorWindow = new CustomChildWindow("Error", "Error de conexion. Intente más tarde.");
                errorWindow.Show();
            }
        }

        private void ChangeLogoSource(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            try
            {
                var uri = new Uri(InputLogo.Text, UriKind.Relative);
                Logo.Source = new BitmapImage(uri);
            }
            catch
            {
                Logo.Source = _defaultLogo;
            }
        }

        private void ChangeLogoSource_Details(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            try
            {
                var uri = new Uri(InputLogo_Details.Text, UriKind.Relative);
                Logo_Details.Source = new BitmapImage(uri);
            }
            catch
            {
                Logo_Details.Source = _defaultLogo;
            }
        }

        /// <summary>
        /// Evento de ingresar nueva compañía.
        /// </summary>
        private void InsertNewCompany(object sender, RoutedEventArgs e)
        {
            var nombre = InputName.Text;
            var cedulaJuridica = InputIdentification.Text;
            /*var logo = Logo.Source;
            var logoPath = InputLogo.Text;*/
            var currency = InputCurrency.SelectedValue.ToString();
            var localCurrency = InputLocalCurrency.SelectedValue.ToString();
            
            if (string.IsNullOrEmpty(nombre))
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese el nombre de la compañía.");
                errorWindow.Show();
            }
            else if (string.IsNullOrEmpty(cedulaJuridica))
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese la cédula jurídica.");
                errorWindow.Show();
            }
            /*else if (logo == _defaultLogo)
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese el logo.");
                errorWindow.Show();
            }*/
            else if (string.IsNullOrEmpty(currency))
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese el nombre de la moneda del sistema.");
                errorWindow.Show();
            }
            else if (string.IsNullOrEmpty(localCurrency))
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese el nombre de la moneda local.");
                errorWindow.Show();
            }
            else
            {
                var company = new Company
                                  {
                                      CompanyName = nombre,
                                      TaxIdentification = cedulaJuridica,
                                      /*Logo = BufferFromImage(logoPath),*/
                                      SystemCurrency = new Currency{ CurrencyName = currency},
                                      LocalCurrency = new Currency { CurrencyName = localCurrency }
                                  };


                InsertNewCompanyCall(company);
                InputName.IsEnabled = false;
                InputIdentification.IsEnabled = false;
                InputLogo.IsEnabled = false;
                InputCurrency.IsEnabled = false;
                InputLocalCurrency.IsEnabled = false;
            }

        }


        /// <summary>
        /// Metodo que convierte un buffer de bytes a una imagen
        /// </summary>
        /// <param name="bytes">Bytes a convertir</param>
        /// <returns>Bitmap Image con la imagen</returns>
        public BitmapImage ImageFromBuffer(Byte[] bytes)
        {
            using (var stream = new MemoryStream(bytes))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var image = new BitmapImage();
                image.SetSource(stream);
                return image;
            }
        }

        /// <summary>
        /// Metodo que permite convertir un path de una imagen a un buffer de bytes
        /// </summary>
        /// <param name="path">Direccion donde se encuentra la imagen</param>
        /// <returns>Buffer de bytes</returns>
        public Byte[] BufferFromImage(string path)
        {
            var streamreader = new StreamReader(path);
            Byte[] buffer = null;
            var stream = streamreader.BaseStream;
            if (stream != null && stream.Length > 0)
            {
                using (var br = new BinaryReader(stream))
                {
                    buffer = br.ReadBytes((Int32)stream.Length);
                }
            }
            return buffer;
        }


        /// <summary>
        /// Evento de editar una compañía.
        /// </summary>
        private void EditCompany(object sender, RoutedEventArgs e)
        {
            var nombre = InputEmpresas.SelectedValue.ToString();
            var cedulaJuridica = InputIdentification_Details.Text;
            /*var logo = Logo_Details.Source;
            var logoPath = InputLogo_Details.Text;*/
            var currency = InputCurrency_Details.SelectedValue.ToString();
            var localCurrency = InputLocalCurrency_Details.SelectedValue.ToString();

            if (string.IsNullOrEmpty(nombre))
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese el nombre de la compañía.");
                errorWindow.Show();
            }
            else if (string.IsNullOrEmpty(cedulaJuridica))
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese la cédula jurídica.");
                errorWindow.Show();
            }
            /*else if (logo == _defaultLogo)
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese el logo.");
                errorWindow.Show();
            }*/
            else if (string.IsNullOrEmpty(currency))
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese el nombre de la moneda del sistema.");
                errorWindow.Show();
            }
            else if (string.IsNullOrEmpty(localCurrency))
            {
                ChildWindow errorWindow = new CustomChildWindow("Debe ingresar todos los datos.", "Por favor ingrese el nombre de la moneda local.");
                errorWindow.Show();
            }
            else
            {
                var company = new Company
                                    {
                                        CompanyId = _company.CompanyId,
                                        CompanyName = nombre,
                                        TaxIdentification = cedulaJuridica,
                                        /*Logo = BufferFromImage(logoPath),*/
                                        SystemCurrency = new Currency { CurrencyName = currency },
                                        LocalCurrency = new Currency { CurrencyName = localCurrency }
                                    };
                _company = company;

                EditCompanyCall(company);
                InputName.IsEnabled = false;
                InputIdentification.IsEnabled = false;
                InputLogo.IsEnabled = false;
                InputCurrency.IsEnabled = false;
                InputLocalCurrency.IsEnabled = false;
            }
        }
        #endregion

        #region Webservice calls
        /// <summary>
        /// Metodo que permite obtener las empresas
        /// </summary>
        public void GetCompanies()
        {
            var client = new MainServiceSilverlightClient();
            client.GetCompaniesCompleted += ClientGetCompaniesCompleted;
            client.GetCompaniesAsync();
        }

        /// <summary>
        /// Metodo que permite obtener las monedas
        /// </summary>
        public void GetCurrencies()
        {
            var client = new MainServiceSilverlightClient();
            client.GetCurrenciesCompleted += ClientGetCurrenciesCompleted;
            client.GetCurrenciesAsync();
        }

        /// <summary>
        /// Método que permite insertar una compañía
        /// </summary>
        /// <param name="company">Compañia que se desea insertar</param>
        public void InsertNewCompanyCall(Company company)
        {
            var client = new MainServiceSilverlightClient();
            client.InsertNewCompanyCompleted += ClientInsertNewCompanyCompleted;
            client.InsertNewCompanyAsync(company);
        }

        /// <summary>
        /// Método que permite editar los datos de una compañía
        /// </summary>
        /// <param name="company"></param>
        public void EditCompanyCall(Company company)
        {
            var client = new MainServiceSilverlightClient();
            //client.EditCompanyCompleted += ClientEditCompanyCompleted;
            //client.EditCompanyAsync(company);
        }
        #endregion

        #region Webservice completeness events for asynchronous calls
        /// <summary>
        /// Evento para la llamada de compañias.
        /// </summary>
        private void ClientGetCompaniesCompleted(object sender, GetCompaniesCompletedEventArgs e)
        {
            if (e.Result == null)
            {
                ChildWindow errorWindow = new CustomChildWindow("Error de Conexión", "Por favor intente más tarde");
                errorWindow.Show();
            }
            else
            {
                InputEmpresas.ItemsSource = e.Result.Select(empresa => empresa.CompanyName).ToList();
                _companies = e.Result.ToList();
            }
        }

        /// <summary>
        /// Evento para la llamada de monedas.
        /// </summary>
        private void ClientGetCurrenciesCompleted(object sender, GetCurrenciesCompletedEventArgs e)
        {
            if (e.Result == null)
            {
                ChildWindow errorWindow = new CustomChildWindow("Error de Conexión", "Por favor intente más tarde");
                errorWindow.Show();
            }
            else
            {
                InputCurrency.ItemsSource = InputLocalCurrency.ItemsSource = InputCurrency_Details.ItemsSource = InputLocalCurrency_Details.ItemsSource = e.Result.Select(moneda => moneda.CurrencyName).ToList();
            }
        }

        /// <summary> 
        /// Evento para la llamada de editar compañia.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ClientEditCompanyCompleted(object sender, InsertNewCompanyCompletedEventArgs e)
        {
            try
            {
                ChildWindow childWindow = new CustomChildWindow("Error en la edicion de empresa", "Se produjo un error a la hora de editar la empresa por favor intentelo nuevamente");
                if (e.Error != null)
                {
                    childWindow.Show();
                }
                if (e.Result)
                {
                    childWindow = new CustomChildWindow("Edición Satisfactoria", "La edición a la empresa ha sido satisfactoria");
                    childWindow.Show();
                }
                else
                {
                    childWindow.Show();    
                }
                InputEmpresas.IsEnabled = true;
                InputIdentification_Details.IsEnabled = true;
                InputLogo_Details.IsEnabled = true;
                InputCurrency_Details.IsEnabled = true;
                InputLocalCurrency_Details.IsEnabled = true;

                InputIdentification_Details.Text = "";
                InputLogo_Details.Text = "";
                Logo_Details.Source = _defaultLogo;
                InputCurrency_Details.SelectedIndex = -1;
                InputLocalCurrency_Details.SelectedIndex = -1; 
            }
            catch (Exception)
            {
                ChildWindow errorWindow = new CustomChildWindow(e.Error);
                errorWindow.Show();
            }
        }

        /// <summary> 
        /// Evento para la llamada de usuario.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ClientInsertNewCompanyCompleted(object sender, InsertNewCompanyCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                {
                    ChildWindow errorWindow = new CustomChildWindow(e.Error);
                    errorWindow.Show();
                }
                if (!e.Result)
                {
                    ChildWindow errorWindow = new CustomChildWindow("Error de Ingreso de empresa", "Se ha producido un error a la hora de añadir una empresa, por favor intente de nuevo");
                    errorWindow.Show();
                }
                InputName.IsEnabled = true;
                InputIdentification.IsEnabled = true;
                InputLogo.IsEnabled = true;
                InputCurrency.IsEnabled = true;
                InputLocalCurrency.IsEnabled = true;

                InputName.Text = "";
                InputIdentification.Text = "";
                InputLogo.Text = "";
                Logo.Source = _defaultLogo;
                InputCurrency.SelectedIndex = -1;
                InputLocalCurrency.SelectedIndex = -1;
            }
            catch (Exception exception)
            {
                ChildWindow errorWindow = new CustomChildWindow("",exception.Message);
                errorWindow.Show();
            }
        }

        #endregion

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {

        }



    }
}
